package hz.mobileproject.pda.callroll.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by Lc on 2017/10/20.
 */

public class BitmapUtil {

    public static byte[] getBytesFromFile(String file) {

        File f = new File(file);
        if(!f.exists()){
            return null;
        }

        if (f == null) {
            return null;
        }
        try {
            FileInputStream stream = new FileInputStream(f);
            ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = stream.read(b)) != -1)
                out.write(b, 0, n);
            stream.close();
            out.close();
            return out.toByteArray();
        } catch (IOException e) {
        }
        return null;
    }

    /**
     * 删除本地图片
     * @param path
     */
    public static void deleteImageFile(String path){
        File file = new File(path);
        if (file.isDirectory()){
            if (file != null && file.exists()) {
                for (File item : file.listFiles()) {
                    item.delete();
                }
            }
        }else {
            if (file != null && file.exists()) {
                file.delete();
            }
        }
    }

    /**
     * 抓拍图片数据存本地
     * @param data
     * @param camera
     * @param path
     */
    public static void saveImageFileByBytes(byte[] data, Camera camera, String path, boolean isBackCamera){

        int width = camera.getParameters().getPreviewSize().width;
        int height = camera.getParameters().getPreviewSize().height;

        final int[] rgb = decodeYUV420SP(data, width, height);

        Bitmap tempBmp = Bitmap.createBitmap(rgb, width, height,Bitmap.Config.ARGB_8888);
        float alpha = 0f;
        if(isBackCamera){
            alpha = -270f;
        }else {
            alpha = -90f;
        }
        Bitmap bmp = rotateBitmap(tempBmp, alpha);
        String filename = path;
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filename);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(null != out){
                out = null;
            }
        }
    }

    /**
     * bitmap旋转
     *
     * @param origin 原图
     * @param alpha  旋转角度，可正可负
     * @return 旋转后的图片
     */
    private static Bitmap rotateBitmap(Bitmap origin, float alpha) {
        if (origin == null) {
            return null;
        }
        int width = origin.getWidth();
        int height = origin.getHeight();
        Matrix matrix = new Matrix();
        matrix.setRotate(alpha);
        // 围绕原地进行旋转
        Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);
        if (newBM.equals(origin)) {
            return newBM;
        }
        origin.recycle();
        return newBM;
    }

    private static int[] decodeYUV420SP( byte[] yuv420sp, int width, int height) {
        final int frameSize = width * height;
        int rgb[]=new int[width*height];
        for (int j = 0, yp = 0; j < height; j++) {
            int uvp = frameSize + (j >> 1) * width, u = 0, v = 0;
            for (int i = 0; i < width; i++, yp++) {
                int y = (0xff & ((int) yuv420sp[yp])) - 16;
                if (y < 0) y = 0;
                if ((i & 1) == 0) {
                    v = (0xff & yuv420sp[uvp++]) - 128;
                    u = (0xff & yuv420sp[uvp++]) - 128;
                }

                int y1192 = 1192 * y;
                int r = (y1192 + 1634 * v);
                int g = (y1192 - 833 * v - 400 * u);
                int b = (y1192 + 2066 * u);

                if (r < 0) r = 0; else if (r > 262143) r = 262143;
                if (g < 0) g = 0; else if (g > 262143) g = 262143;
                if (b < 0) b = 0; else if (b > 262143) b = 262143;

                rgb[yp] = 0xff000000 | ((r << 6) & 0xff0000) | ((g >> 2) &
                        0xff00) | ((b >> 10) & 0xff);

            }
        }
        return rgb;
    }

    /**
     * 本地图片转bitmap
     * @param image
     * @return
     */
    public static Bitmap getBitmapByFaceApp(String image){
//        BitmapFactory.Options opts = new BitmapFactory.Options();//ARGB_8888
//        opts.inPreferredConfig = RGB_565;
//        return BitmapFactory.decodeFile(image,opts);
        //图片压缩
        Bitmap bmSrc = getImageThumbnail(image, 480, 800, false);
        return bmSrc;
    }
    /**
     * 本地图片压缩后转bitmap
     * @param imagePath
     * @param maxWidth
     * @param maxHeight
     * @return
     */
    private static Bitmap getImageThumbnail(String imagePath, int maxWidth,
                                            int maxHeight, boolean isDeleteFile) {
        Bitmap bitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        options.inJustDecodeBounds = false;
        options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight);
        FileInputStream inputStream = null;
        File file = new File(imagePath);
        try {
            if(file != null && file.exists()){
                inputStream = new FileInputStream(file);
                bitmap = BitmapFactory.decodeStream(inputStream, null,options);
                if(isDeleteFile){
                    file.delete();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null)
                    inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return bitmap;
        }
    }

    private static int calculateInSampleSize(BitmapFactory.Options options,
                                             int reqWidth, int reqHeight) {
        // 源图片的高度和宽度
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            // 计算出实际宽高和目标宽高的比率
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            // 选择宽和高中最小的比率作为inSampleSize的值，这样可以保证最终图片的宽和高
            // 一定都会大于等于目标的宽和高。
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }


    /**
     * bitmap转BGR字节数组
     * @param bmSrc
     * @return
     */
    public static byte[] getBGRByteByBitmap(Bitmap bmSrc){
        int width = bmSrc.getWidth();
        int height = bmSrc.getHeight();
        int[] rgba = new int[width * height];
        byte[] bgr = new byte[width * height * 3];
        bmSrc.getPixels(rgba, 0, width, 0, 0, width, height);
        final int frameSize = width * height;
        int index = 0;
        int r, g, b, a, y, u, v;
        for (int j = 0; j < height; j++) {
            for (int i = 0; i < width; i++) {
                a = (rgba[index] & 0xff000000) >> 24;
                r = (rgba[index] & 0xff0000) >> 16;
                g = (rgba[index] & 0xff00) >> 8;
                b = (rgba[index] & 0xff);
                bgr[index * 3] = (byte) ((b < 0) ? 0 : ((b > 255) ? 255 : b));
                bgr[index * 3 + 1] = (byte) ((g < 0) ? 0 : ((g > 255) ? 255 : g));
                bgr[index * 3 + 2] = (byte) ((r < 0) ? 0 : ((r > 255) ? 255 : r));
                index++;
            }
        }

        return bgr;
    }

}
